package org.example.rental.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.rental.common.Result;
import org.example.rental.domain.Rate;
import org.example.rental.domain.RentalOrder;
import org.example.rental.service.RateService;
import org.example.rental.service.RentalOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/rate")
public class RateController extends BaseController {


    @Autowired
    RateService rateService;

    @Autowired
    RentalOrderService rentalOrderService;



    @PostMapping("/addRate")
    @Transactional
    public Result addRate(@RequestBody Rate rate){
        RentalOrder order = rentalOrderService.getById(rate.getOrderId());
        rate.setRateTime(new Date());
        rate.setPhone(order.getPhone());
        rate.setUsername(order.getUsername());
        rate.setGoodsId(order.getGoodsId());
        rate.setUserId(order.getUserId());

        rateService.save(rate);

        order.setRateState(1);
        rentalOrderService.updateById(order);

        return Result.succ(rate);

    }

    @GetMapping("/selectPage/{id}")
    public Result selectPage(@PathVariable("id")Integer goodsId ){
        QueryWrapper<Rate> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",goodsId);

        Page<Rate> page = rateService.page(getPage(), wrapper);
        List<Rate> list = page.getRecords();
        for (Rate rate : list) {
            rate.setPhone(rate.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        }
        page.setRecords(list);
        return Result.succ(page);
    }





}
